package cool.zhoujie.address;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.navigation.Navigation;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import cool.zhoujie.address.databinding.FragmentEditBinding;
import cool.zhoujie.address.db.Address;
import cool.zhoujie.address.db.AddressDao;
import cool.zhoujie.address.db.AddressDatabase;

public class EditFragment extends Fragment {

    private Address mAddress;

    private AddressDao mDao;

    public MutableLiveData<Boolean> isDefault = new MutableLiveData<>();

    public EditFragment() {
        mDao = AddressDatabase.getInstance().mAddressDao();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mAddress = (Address) getArguments().getSerializable("address");
        isDefault.setValue(mAddress.isDefault);
        FragmentEditBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_edit, container, false);
        binding.setFragment(this);
        binding.setLifecycleOwner(this);
        binding.setAddress(mAddress);
        return binding.getRoot();
    }

    public void navigate(View view) {
        Navigation.findNavController(view).navigate(R.id.action_editFragment_to_showFragment);
    }

    //修改address的default
    public void setDefault() {
        mAddress.isDefault = !mAddress.isDefault;
        isDefault.setValue(mAddress.isDefault);
    }

    //保存并跳转到展示碎片
    public void save(View view) {
        mDao.update(mAddress);

        Navigation.findNavController(view).navigate(R.id.action_editFragment_to_showFragment);
    }
}
